import { filterClassNames } from './filterClassNames';
import { EXT_NAME, GENERATE, CSS_ANNOTATION, ROOT, BEFORE_CONTENTS, AFTER_CONTENT, AUTO_USE_SNIPPETS, ROOT_DIR, CSS_FILE_NAME, CSS_FILE } from '../constant';
import { getConfig } from '../config';
import { renderCss } from './preRender';
import { generator } from './genSnippets';

const fs = require('fs');
const fs2 = fs.promises;
const path = require('path');
const glob = require('glob');
const { performance } = require('perf_hooks');

const writeToFile = async () => {
	const cssFilePath = path.resolve(process.env.UNI_INPUT_DIR || '', getConfig(ROOT) || ROOT_DIR, getConfig(CSS_FILE) || CSS_FILE_NAME);
	const cssDirPath = path.dirname(cssFilePath);
	// 检查目录是否存在，如果不存在则创建
	if (!fs.existsSync(cssDirPath)) {
		await fs2.mkdir(cssDirPath, { recursive: true }); // 使用 recursive: true 来创建所有必要的上级目录
	}

	const cssStr = `${getConfig(BEFORE_CONTENTS) || ''}\n${CSS_ANNOTATION}${renderCss()}${getConfig(AFTER_CONTENT) || ''}`;
	
	// 读取现有文件的内容
	let existingContent;
	try {
		existingContent = await fs2.readFile(cssFilePath, 'utf8');
	} catch (error) {
		if (error.code === 'ENOENT') { // 文件不存在
			existingContent = null;
		} else {
			throw error; // 其他错误，抛出异常
		}
	}
	
	// 如果内容有变化，则写入新内容
	if (cssStr !== existingContent) {
		await fs2.writeFile(cssFilePath, cssStr);
	}
}

const readFile = (path : any) => {
	if (fs.existsSync(path) && fs.statSync(path).isFile()) {
		return fs.readFileSync(path, 'utf8');
	}

	return '';
}

// const getAllFileClassStr = () => {
// 	const globSyncStr = getConfig(EXT_NAME).join('|');
// 	// 暂时这么处理，后续优化
// 	const files = glob.sync(`**/*.@(${globSyncStr})`, {
// 		ignore: ["node_modules/**"]
// 	});
// 	return files.reduce((t : any, c : any) => t + readFile(path.resolve(c)), '');
// }

let startTime = 0;
let endTime = 0;
let isHotReload = false;

const setTimeStart = () => {
	startTime = performance.now();
}

const setTimeEnd = () => {
	endTime = performance.now();
}

const getUseTime = () => (endTime - startTime).toFixed(2);

const logUseTime = () => {
	console.log(`autocss 生成器${isHotReload ? '重载' : '初始化'}完成， 用时 ${getUseTime()}ms`);
}

// export const init = (compiler : any = null) => {
// 	setTimeStart();
// 	filterClassNames(getAllFileClassStr());
// 	writeToFile();
// 	if (getConfig(AUTO_USE_SNIPPETS)) {
// 		generator();
// 	}
// 	setTimeEnd();
// 	if (compiler) {
// 		compiler.hooks.done.tap('autocss-generator-done', logUseTime);
// 	} else {
// 		logUseTime();
// 	}
// }

export const hotReload = async (txt : string, extName = 'uvue') => {
	setTimeStart();
	filterClassNames(txt, extName);
	writeToFile();
	const cssStr = `${getConfig(BEFORE_CONTENTS) || ''}\n${CSS_ANNOTATION}${renderCss()}${getConfig(AFTER_CONTENT) || ''}`;
	// console.log(cssStr);
	// 生成内联样式
	txt += `\n<style>\n${cssStr}\n</style>`;
	if (getConfig(AUTO_USE_SNIPPETS)) {
		generator();
	}
	setTimeEnd();
	logUseTime();
	// if (process.env.UNI_PLATFORM === 'app') {
	// 	return txt
	// }
	return {
		css: cssStr,
		sourceCode: txt
	}
	// hotReload = true;
	// return txt
}